// scripts/deploy.js
const { ethers, artifacts } = require("hardhat");
const fs = require("fs");

async function main() {
  const [deployer] = await ethers.getSigners();
  console.log("Deploying contract with account:", deployer.address);

  // 部署 NftMarket 合约
  const NftMarket = await ethers.getContractFactory("NftMarket");
  const nftMarket = await NftMarket.deploy(); // v6: 直接 await 不用 .deployed()
  await nftMarket.waitForDeployment(); // ethers v6 的写法，等待链上确认

  const address = await nftMarket.getAddress(); // ethers v6 获取合约地址

  console.log("NftMarket contract deployed to:", address);

  // 输出 ABI 和地址到前端目录
  const contractArtifact = await artifacts.readArtifact("NftMarket");
  // 保证前端 contracts 目录存在
  const targetDir = "frontend/src/contracts";
  if (!fs.existsSync(targetDir)){
    fs.mkdirSync(targetDir, { recursive: true });
  }
  fs.writeFileSync(
    `${targetDir}/NftMarket.json`,
    JSON.stringify({ address, abi: contractArtifact.abi }, null, 2)
  );
  console.log("ABI & address exported to frontend/src/contracts/NftMarket.json");
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});
